/*
 * @Author: 偻儸小卒[EdisonLiu_]
 * @Date: 2021-03-18 19:13:16
 * @LastEditors: 偻儸小卒[EdisonLiu_]
 * @LastEditTime: 2021-03-19 08:45:28
 * @Description: 
 */
package cmd


import (
	"ginblog/utils/errmsg"
	"ginblog/model"
	"gorm.io/gorm"
	"fmt"
	
)
type User struct {
	gorm.Model
	Username string `gorm:"type:varchar(20);not null " json:"username" validate:"required,min=4,max=12" label:"用户名"`
	Password string `gorm:"type:varchar(500);not null" json:"password" validate:"required,min=6,max=120" label:"密码"`
	Role     int    `gorm:"type:int;DEFAULT:2" json:"role" validate:"required,gte=2" label:"角色码"`
	Id     int    `gorm:"type:int;DEFAULT:2" json:"id" validate:"required,gte=2" label:"编号"`
}


type modelUser struct {
	gorm.Model
	Username string `gorm:"type:varchar(20);not null " json:"username" validate:"required,min=4,max=12" label:"用户名"`
	Password string `gorm:"type:varchar(500);not null" json:"password" validate:"required,min=6,max=120" label:"密码"`
	Role     int    `gorm:"type:int;DEFAULT:2" json:"role" validate:"required,gte=2" label:"角色码"`
}


func changePwd(userdata * CmdData)  {
	//这里用model 自动处理总是不成功， 报错 runtime error: invalid memory address or nil pointer dereference 所以就复写了一遍db类 然后直接调用一下
	InitDb()
	var udata User
	// var username=userdata.Username
	// fmt.Println(userdata.Username)

	// code = model.CheckUser(data.Username)
	data, code :=ChGetUser(userdata.Username)
	if data.Id==0||code != 200 {
		fmt.Println("查无此人！")
	}else{
		udata.Password=model.ScryptPw(userdata.Pwd)
		code= ChangePassword(data.Id, &udata)
		if code != 200 {
			fmt.Println("操作失败！")
		}
	}
	fmt.Println("操作成功！")
	// // code:= model.ChangePassword(user.id, &data)
	// fmt.Println("修改成功")
	// c.JSON(
	// 	http.StatusOK, gin.H{
	// 		"status":  code,
	// 		"message": errmsg.GetErrMsg(code),
	// 	},
	// )
}
// 查询用户
func ChGetUser(username string) (User, int) {
	var user User
	err := db.Limit(1).Where("username = ?", username).Find(&user).Error
	if err != nil {
		return user, errmsg.ERROR
	}
	return user, errmsg.SUCCSE
}


// 修改密码
func ChangePassword(id int, data *User) int {
	err = db.Select("password").Where("id = ?", id).Updates(&data).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCSE
}

